extends Area2D

enum {MOVE, STOP}
var speed = 0				# 靠近速度
var accileration = 0		# 加速度
var friction = 0			# 摩擦力

@onready var parent = $".."
@onready var animation = $"../AnimatedSprite2D"

var state = STOP
var player = null
var velocity = Vector2.ZERO

func _ready():
	speed = parent.speed
	accileration = parent.accileration
	friction = parent.friction
	connect("area_entered", inSeeArea)
	connect("area_exited", outSeeArea)
	
func _physics_process(delta):
	match state:
		MOVE:
			move(delta)
		STOP:
			stop(delta)
	
	# 模拟碰撞的行走
	# 对象碰撞到刚体会被定在原地
	parent.move_and_collide(velocity * delta)
	

'''
	靠近玩家
'''
func move(delta):
	if player != null:
		# 玩家所在坐标 - 当前本体所在坐标 = 前进的方向
		var direction = player.global_position - global_position
		# 再将方向进行勾股定理转换, 以免斜线速度发生变化
		direction = direction.normalized()
		
		# 保存当前的方向, 让敌人也可以撞击方块
		parent.direction = direction
		'''
			enemy对象的向量, 以accileration * delta的速度, 靠近speed * direction
				- speed: 最大速度
				- direction: 方向
		'''
		parent.velocity = parent.velocity.move_toward(speed * direction, accileration * delta)
		animation.flip_h = direction < Vector2.ZERO


'''
	停止
'''
func stop(delta):
	'''
		enemy对象的向量, 以delta * friction速度缓慢靠近Vector2.ZERO
		Vector2.ZERO代表: 无方向, 无速度
	'''
	parent.velocity = parent.velocity.move_toward(Vector2.ZERO, delta * friction)
	
'''
	进入区域
	@param area 进入区域的碰撞体
'''
func inSeeArea(area):
	state = MOVE
	player = area.get_parent()


'''
	退出区域
'''
func outSeeArea(_area):
	state = STOP
	player = null
